var masterRateItemsARArray;
var masterRateItemsAPArray;
var masterRateCodesARArray;
var masterRateCodesAPArray;

var currentEle;
(function($){

    $.fn.quiggleDynamicJobAdd = function (templateBlock, placeHolder, indexBlock){
        $(this).click(function(){
//            alert("add address click " + templateBlock);
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
//            alert("index " + index);
            var templateClone = template.clone();
//            alert(templateClone.html());
            templateClone.html(templateClone.html().replace(/{index}/g, index));
            templateClone.attr('id', template.attr('id') + '-' + index)
//            templateClone.removeClass('template');
            templateClone.insertAfter($(placeHolder));
//            alert(templateClone.html());
            indexField.text(index + 1);
            templateClone.bindJobEvents();
            var statusField = templateClone.find("[name='job.statusId']");
//            alert(statusField.attr("name"));
            statusField.focus();
        });
    };

    $.fn.quiggleJobAutoComplete = function(dataSource, idField, dialogForm,nobrace,innerid){

        $( this ).autocomplete({
            minLength: 0,
//                source: projects,
            source: dataSource,
            focus: function( event, ui ) {
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
                return false;
            },
            
            select: function( event, ui ) {
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
//                    $( "#project-id" ).val( ui.item.value );
//                alert("change " + ui.item.id);
                $( this ).parent().find(idField).val( ui.item.id );
                if(innerid == 'agencylink'){
                	var jobId = $(this).closest(".job-table").find(".selectedjobid").val();
                	$("#agencylink"+jobId).html("<a href='javascript:{getRateTableId("+ui.item.id+","+jobId+",\"AGENCY\")}'>"+ui.item.initial+"</a>");
                	$(this).closest(".job-table").find(".callAjaxTGetAgencyCodes").val("");
                	$(this).closest(".job-table").find(".type-id").val(0);
                	$(this).closest(".job-table").find(".jobtypetext").html("");
                }
                else if(innerid == 'agencytypelink'){
                	$(this).closest(".job-table").find(".jobtypetext").html(ui.item.initial);
                }
                else if(innerid == 'scopistlink'){
                	var jobId = $(this).closest(".job-table").find(".selectedjobid").val();
                	if(actualUserId != ui.item.id)
                	 $("#scopistlink"+jobId).html("<a href='javascript:{getRateTableId("+ui.item.id+","+jobId+",\"SCOPIST\")}'>"+ui.item.initial+"</a>");
                	else
                		$("#scopistlink"+jobId).html("Self");
                	$("#scopistRateId"+jobId).val(0);
                }
                else if(innerid == 'prooferlink'){
                	var jobId = $(this).closest(".job-table").find(".selectedjobid").val();
                	if(actualUserId != ui.item.id)
                	  $("#prooferlink"+jobId).html("<a href='javascript:{getRateTableId("+ui.item.id+","+jobId+",\"PROOFER\")}'>"+ui.item.initial+"</a>");
                	else
                		$("#prooferlink"+jobId).html("Self");
                	$("#prooferRateId"+jobId).val(0);
                }
//                    $( "#project-description" ).html( ui.item.desc );
//                    $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );

                return false;
            },
            change: function(event, ui){
            	
            	var textval=$.trim($(this).val()).toLowerCase();
    			var flag=true;
    			for (var i = 0; i < dataSource.length; i++) {
    				if ($.trim(dataSource[i].initial).toLowerCase() == textval) {
    					flag=false;
    					$( this ).parent().find(idField).val(dataSource[i].id);
    				}
    			}
    			
    			if(textval=="")
    				flag=false;
    			
                if(ui.item === null && flag){
	                if($(idField).hasClass("type-id")){
	                    var userInputCode=$(this).val();
	                    var agencyId=$(idField).closest(".job-table").find(".agency-id").val();                    	
             			var jobId=$(idField).closest(".job-table").find(".selectedjobid").val();
             			
             			
             			
             			
	                  /*  if($.inArray(userInputCode.toLowerCase(), masterRateCodesARArray)!=-1){
	                    	getRateTableId(agencyId,jobId,'AGENCY', false, userInputCode);     
	                    }
	                    else{*/
                 			getRateTableId(agencyId,jobId,'AGENCY', true, userInputCode);
	                    //}
	                   
                    }
	                else{
	                	$(this).parent().find(idField).val('');
		                 $(dialogForm).find(".block-id").val($(this).parent().attr("id"));
		                 $(dialogForm).find(".initial").val($(this).val());
		                 $( dialogForm ).dialog("open");
	                }
                  
					currentEle=idField;
                }
                return false;
            }
        })
            .data( "autocomplete" )._renderItem = function( ul, item ) {
        	if(nobrace == 1){
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.initial  + "</a>" )
                .appendTo( ul );}
        	else{
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.initial + " (" +item.firstName + item.lastName + ")" + "</a>" )
                    .appendTo( ul );}
        };

    };

    $.fn.bindJobEvents = function(){

        $(this).find('.edit-job').each(function(){

            $(this).click(function(){
                $(this).closest(".job-record-block").find('.view').hide();
                $(this).closest(".job-record-block").find('.edit').show();
                $(this).closest(".job-record-block").find("[name='job.statusId']").focus();
				//$(this).closest(".job-record-block").find(':input[value=""].edit:first').focus();
				$(this).closest(".job-record-block").find(':input.edit:first').focus();
            })
        });

        $(this).find('.cancel-edit').each(function(){
            $(this).click(function(){
            	
                     $(this).closest(".job-record-block").find('.edit').hide();
                    $(this).closest(".job-record-block").find('.view').show();
					$(this).closest(".job-record-block").find(".ketchup-errorPar").remove();
            	
            })
        });


        $(this).find(".date-picker").each(function(){
            $(this).removeClass('hasDatepicker');
            $(this).datepicker();
        });

        $(this).find(".agency-initial").each(function(){
            $(this).quiggleJobAutoComplete(agencies, '.agency-id', "#agency-form",0,'agencylink');
        });

        $(this).find(".scopist-initial").each(function(){
            $(this).quiggleJobAutoComplete(scopists, '.scopist-id', "#scopist-form",0,'scopistlink');
        });

        $(this).find(".proofer-initial").each(function(){
            $(this).quiggleJobAutoComplete(proofers, '.proofer-id',"#proofer-form",0,'prooferlink');
        });



    };

})(jQuery);


$(document).ready(function(){
	$('.billingestimatePages').live("change",function(){

//var jobId= $(this).closest(".job-row").find('.jobId').val();

$("#estimatePages-form").dialog({
height: 350,
width: 600,
modal: true,
title:"MY HOURS TO PERFORM TASK",
hide: 'fold',
show: 'blind',
buttons: {

"Save":function(){
saveAdminstrativeHoursInJob(actualUserId,jobId);
},
"Cancel": function() {
$('.billingestimatePages').closest("div").next().find("input:visible").focus();
$(this).dialog('close');
}
},

});
$('.ui-icon').click(function(){
		
$('.billingestimatePages').closest("div").next().find("input:visible").focus();
});
callAjaxToDisplayAdminstrativeHours(actualUserId,jobId);
});


	$("#instructionsHideLinkForQGL").live("click",function(){

	  $("#contentInsForQGL").hide();
	  $("#instrutionsSpanForQGL").html("<a title='click here to show the instructions' id='instructionsShowLinkForQGL' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsDownarrowimg' src='images/downarrow.png' width='10' height='9' alt='Hide' /></a>");
	});
						

	$("#instructionsShowLinkForQGL").live("click",function(){
	  $("#contentInsForQGL").show();
	  $("#instrutionsSpanForQGL").html("<a title='click here to hide the instructions' id='instructionsHideLinkForQGL' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsuparrowimg' src='images/uparrow.png' width='10' height='9' alt='Hide' /></a>");

	}); 

	$(".initial").blur(function(){
		var initial=$(this).val();
		var initials=initial.toUpperCase();
	
		var upperCasedAgencyArray = new Array();
		var upperCasedScopistArray = new Array();
		var upperCasedProoferArray = new Array();
	
		$.each(agyIntlsArray, function(index, item) {
		upperCasedAgencyArray[index] = item.toUpperCase();
		});
		$.each(scpIntlsArray, function(index, item) {
		upperCasedScopistArray[index] = item.toUpperCase();
		});
		$.each(prfIntlsArray, function(index, item) {
		upperCasedProoferArray[index] = item.toUpperCase();
		});
		//var upperCasedAgencyArray = $.map(agyIntlsArray, String.toUpperCase);
		//var upperCasedScopistArray = $.map(scpIntlsArray, String.toUpperCase);
		//var upperCasedProoferArray = $.map(prfIntlsArray, String.toUpperCase);
		if($(this).attr("id")=="agency-initial"){
			if($.inArray(initials, upperCasedAgencyArray)!=-1){			
				$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
				$(this).parent().next().find("input").val(initials);
				$(this).parent().next().css("display", "none");
				$(this).parent().parent().next().css("display", "block");
			}
			else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create an agency");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#agency-name').val('');
			}
		}
		else if($(this).attr("id")=="scopist-initial"){
			if($.inArray(initials, upperCasedScopistArray)!=-1){			
				$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
				$(this).parent().next().find("input").val(initials);
				$(this).parent().next().css("display", "none");
				$(this).parent().parent().next().css("display", "block");
			}
			else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a scopist");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#scopist-name').val('');
			}
		}
		else if($(this).attr("id")=="proofer-initial"){
			if($.inArray(initials, upperCasedProoferArray)!=-1){			
				$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
				$(this).parent().next().find("input").val(initials);
				$(this).parent().next().css("display", "none");
				$(this).parent().parent().next().css("display", "block");
			}
			else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a proofer");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#proofer-name').val('');
			}
		}
		
	});
$(".ui-dialog-buttonset button").live("click",function(){

var hasclass=$(currentEle).closest("div").hasClass("notes");
//alert(hasclass);
if(hasclass){$(currentEle).closest(".job-row").find(".actul-turned-in").find("input:visible").focus();}
$(currentEle).closest("div").next().find("input:visible").focus();
});

$(".date-picker").live("change",function(){
//alert("TEST");
/*var val=$(this).val();
if(val.length>0)*/
$(this).closest("div").find("input:visible").focus();
});
    $(this).bindJobEvents();

   // $("#add-job").quiggleDynamicJobAdd("#job-template", "#job-placeholder", "#job-index");

});




$(function() {
    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
//		$( "#dialog:ui-dialog" ).dialog( "destroy" );

    var name = $( "#name" ),
        email = $( "#email" ),
        password = $( "#password" ),
        allFields = $( [] ).add( name ).add( email ).add( password ),
        tips = $( ".validateTips" );

    var agencyInitial = $("#agency-initial"),
        agencyName = $("#agency-name"),
        allAgencyFields = $([]).add(agencyInitial).add(agencyName),
        agencyTips = $(".agency-validation-tips");


    function updateTips( t ) {
        tips
            .text( t )
            .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }

    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }

    $( "#agency-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create an agency": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                	var block = $(this).find('.block-id').val();
                
                	 var agency = $('#' + block);

                     
                     agency.find('.agency-initial').val($("#agency-initial").val());
                     agency.find('.agency-name').val($("#agency-name").val());
                     agency.closest(".job-table").find(".callAjaxTGetAgencyCodes").val("");
                     agency.closest(".job-table").find(".type-id").val(0);
                     $(this).closest(".job-table").find(".jobtypetext").html("");
           			var initial = $("#agency-initial").val();
                     var name = $("#agency-name").val();
					 var eFlag = false;
					 var str ='';
					
                     if($.trim(initial) == "")
					 {
						 str +='Initial is Required.';
						 eFlag = true;
				   	 }
					 if($.trim(name) == "")
					 {
						 str +='Name is Required.';
						 eFlag = true;
				   	 }
					 

					 $("#agency-form-ErrorMsgDiv").html(str);
					 if(eFlag)
						 return;

                	var agencyval ={     
                			"initial":initial,
                			"name":name		
                			
                	};
                	 $.ajaxSetup({
              		   jsonp: null,
              		   jsonpCallback: null
              		});

              	    $.ajax({
              		  type:'POST',
              		  url: 'qgl-log-detail-accounting.action?createAgency',
              		  dataType: 'json',
              		  data: {agency:JSON.stringify(agencyval)},
              		  success: function(result){
              			agency.find('.agency-id').val(result);
              			var obj = {
             			};

             	         obj["value"] = initial+" "+name;
             	         obj["id"] = result;
             	         obj["initial"] =initial;
             	         obj["lastName"] = name;
             	         obj["firstName"] = name;
                       agencies.push(obj);
                       var jobId = agency.closest(".job-table").find(".selectedjobid").val();
                       $("#agencylink"+jobId).html("<a href='javascript:{getRateTableId("+result+","+jobId+",\"AGENCY\")}'>"+initial+"</a>");
                           $(".agency-initial").quiggleJobAutoComplete(agencies, '.agency-id', "#agency-form",0,'agencylink');
              		 },
              		  error:function() { 
              			  
              		  }
                 	});
                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	var block = $(this).find('.block-id').val();
           	    var agency = $('#' + block);
           	    var jobId = agency.closest(".job-table").find(".selectedjobid").val();
           	 $("#agencylink"+jobId).html("");
           	 agency.closest(".job-table").find(".type-id").val(0);
           	agency.closest(".job-table").find(".callAjaxTGetAgencyCodes").val(""); 
           	agency.closest(".job-table").find(".jobtypetext").html("");
           	agency.closest(".job-row").find(".agency-id").val(0);
           	agency.closest(".job-table").find(".agency-initial").val("");
        	agency.closest(".job-table").find(".agency-initial").focus();

           	$( this ).dialog( "close" );
            }
        },
        close: function(event, ui) {
        	if ( event.originalEvent && 
                      $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
        		var block = $(this).find('.block-id').val();
           	    var agency = $('#' + block);
           	    var jobId = agency.closest(".job-table").find(".selectedjobid").val();
           	    $("#agencylink"+jobId).html(""); 	
           	    agency.closest(".job-table").find(".type-id").val(0);
            	agency.closest(".job-table").find(".callAjaxTGetAgencyCodes").val(""); 
            	agency.closest(".job-table").find(".jobtypetext").html("");
            	agency.closest(".job-row").find(".agency-id").val(0);
            	agency.closest(".job-table").find(".agency-initial").val("");
            	agency.closest(".job-table").find(".agency-initial").focus();

            }
        	
        	allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            $(this).closest(".ui-dialog").find(".ui-button:first span").text("Create an agency");
            $(this).find("#agency-name").val("");
			$(this).find("#agency-name").parent().css("display", "block");
			$(this).find("#agency-name").parent().parent().next().css("display", "none");
        }
    });
    
    $( "#agency-form1" ).dialog({
        autoOpen: false,
        height: 250,
        width: 950,
        modal: true,
        buttons: {
            "Create a proofer new rate item": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    
                    var id=agency.find('.proofer-rate-item-id').attr('id');
                    
                    agency.find('.proofer-rate-item-id').val('0');                    
                    agency.find('.proofer-rate-item-code').val($('#proofer-rate-item-code').val());
                    agency.find('.proofer-rate-item-code-description').val($('#proofer-rate-item-code-description').val());
                    agency.find('.proofer-rate-item-value').val($('#proofer-rate-item-value').val());
                    agency.find('.proofer-rate-item-unit').val($('#proofer-rate-item-unit').val());
                    agency.find('.proofer-rate-item-perunit').val($('#proofer-rate-item-perunit').val());
                    agency.find('.proofer-rate-item-reimbursable').val($('#proofer-rate-item-reimbursable').val());
                    agency.find('.proofer-rate-item-taxable').val($('#proofer-rate-item-taxable').val());
                    agency.find('.proofer-rate-item-perunit-expedite').val($('#proofer-rate-item-perunit-expedite').val());
                    agency.find('.proofer-rate-item-code').focus();
                    var perunitval = 0;
                    if($('#proofer-rate-item-unit').val() == "2")
                 	   perunitval = $('#proofer-rate-item-perunit-expedite').val();
                    else
                 	   perunitval = $('#proofer-rate-item-perunit').val();
                 	   
				   var code = $('#proofer-rate-item-code').val();
				   var value = $('#proofer-rate-item-value').val();
				   var str = '';
				   var eFlag = false;
					if($.trim(code) == "")
					{
						str +='Code is Required.';
						eFlag = true;
					}
					if($.trim(value) =="")
					{
						str +='Value is Required.';
						eFlag = true;
					}
					else if(isNaN(value))
					{
						str +='Enter Numeric Value.';
						eFlag = true;
					}
					$("#agency-form1-errorMsgDiv")
					if(eFlag)
						return;
				  
                    var rateItemDetails={                    		
                    		
    						code:code,
    						codeDescription:$('#proofer-rate-item-code-description').val(),
    						value:value,
    						unit:$('#proofer-rate-item-unit').val(),
    						perUnit:perunitval,
    						reimbursable:$('#proofer-rate-item-reimbursable').is(":checked"),
    						taxable:$('#proofer-rate-item-taxable').is(":checked") ,
    						entityUserId:$('.proofer-id').val(),
    						type:"PROOFER",
    						ccval:0,
    						jobId:agency.find('.proofer-job_id').val()
    						
                        };
                    
                    callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,id);

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
//            alert($(this).attr("id"));
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
        }
    });

   $( "#scopist-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a scopist": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );

                if ( bValid ) {
                	 var block = $(this).find('.block-id').val();
                	 var agency = $('#' + block);

                     
                     agency.find('.scopist-initial').val($("#scopist-initial").val())
                     agency.find('.scopist-name').val($("#scopist-name").val())
                     agency.find('.scopist-initial').focus();
                     agency.closest(".job-table").find(".scopist-rate-item-code").val("");
                     agency.closest(".job-table").find(".scopist-rate-item-id").val(0);
                     var initial = $("#scopist-initial").val();
                     var name = $("#scopist-name").val();
                     var jobId = agency.closest(".job-table").find(".selectedjobid").val();
					 var str ='';
					 var eFlag = false;

					 if($.trim(initial) == "")
					 {
						 str += "Initial is Required.";
						 eFlag = true;
					 }
					 if($.trim(name) == "")
					 {
						 str += "Name is Required.";
						 eFlag = true;
					 }
					 $("#scopist-form-ErrorMsgDiv").html(str);
					if(eFlag)
						return;
                     var scopistval ={     
                 			"initial":initial,
                 			"name":name		
                 			
                 	};
                 	 $.ajaxSetup({
               		   jsonp: null,
               		   jsonpCallback: null
               		});

               	    $.ajax({
               		  type:'POST',
               		  url: 'qgl-log-detail-accounting.action?createScopist',
               		  dataType: 'json',
               		  data: {scopist:JSON.stringify(scopistval)},
               			 
               		  success: function(result){
               			  
               			agency.find('.scopist-id').val(result);
              			var obj = {
             			};

             	         obj["value"] = initial+" "+name;
             	         obj["id"] = result;
             	         obj["initial"] =initial;
             	         obj["lastName"] = name;
             	         obj["firstName"] = name;
             	        scopists.push(obj);
             	       $("#scopistlink"+jobId).html("<a href='javascript:{getRateTableId("+result+","+jobId+",\"SCOPIST\")}'>"+initial+"</a>");
             	      $("#scopistRateId"+jobId).val(0);
             	       $(".scopist-initial").quiggleJobAutoComplete(scopists, '.scopist-id', "#scopist-form",0,'scopistlink');
                 
               		    
               		 },
               		  error:function() { 
               			  
               		  }
                  	});
                   

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	 var block = $(this).find('.block-id').val();
            	 var agency = $('#' + block);
            	 var jobId = agency.closest(".job-table").find(".selectedjobid").val();
            	 $("#scopistlink"+jobId).html("");
            	 agency.closest(".job-row").find(".scopist-id").val(0);
            	 $("#scopistRateId"+jobId).val(0);
            	 agency.closest(".job-row").find(".scopist-initial").val("");
            	 agency.closest(".job-row").find(".scopist-initial").focus();
                $( this ).dialog( "close" );
            }
        },
        close: function(event, ui) {
          if ( event.originalEvent && 
                      $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
        	  var block = $(this).find('.block-id').val();
         	 var agency = $('#' + block);
         	 var jobId = agency.closest(".job-table").find(".selectedjobid").val();
         	 $("#scopistlink"+jobId).html("");	
	         	agency.closest(".job-row").find(".scopist-id").val(0);
       	 		$("#scopistRateId"+jobId).val(0);
	         	agency.closest(".job-row").find(".scopist-initial").val("");
	       	 	agency.closest(".job-row").find(".scopist-initial").focus();
            }
        	
        	allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            $(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a scopist");
            $(this).find("#scopist-name").val("");
			$(this).find("#scopist-name").parent().css("display", "block");
			$(this).find("#scopist-name").parent().parent().next().css("display", "none");
        }
    });
   
   
   $( "#agency-rate-item-form" ).dialog({
       autoOpen: false,
       height: 250,
       width: 950,
       modal: true,
       buttons: {
           "CreateNewAgencyRateItem" : {
        	   text: "Create a new agency rate item",
        	   id: "createNewRate",
        	   click: function() {
               var bValid = true;
               allAgencyFields.removeClass( "ui-state-error" );

//               bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
               // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

               if ( bValid ) {
                   
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + name.val() + "</td>" +
                    "<td>" + email.val() + "</td>" +
                    "<td>" + password.val() + "</td>" +
                    "</tr>" );
                    
                  
                    
                   var block = $(this).find('.block-id').val();
                   var agency = $('#' + block);

              
                   agency.find('.agency-rate-item-code').val($('#agency-rate-item-code').val());
                   agency.find('.agency-rate-item-code-description').val($('#agency-rate-item-code-description').val());
                   agency.find('.agency-rate-item-value').val($('#agency-rate-item-value').val());
                   agency.find('.agency-rate-item-unit').val($('#agency-rate-item-unit').val());
                   agency.find('.agency-rate-item-perunit').val($('#agency-rate-item-perunit').val());
                   agency.find('.agency-rate-item-reimbursable').val($('#agency-rate-item-reimbursable').val());
                   agency.find('.agency-rate-item-taxable').val($('#agency-rate-item-taxable').val());
                   agency.find('.agency-rate-item-perunit-expedite').val($('#agency-rate-item-perunit-expedite').val());                    

                   agency.find('.agency-rate-item-code').focus();
                   agency.closest(".job-table").find(".jobtypetext").html($('#agency-rate-item-code').val());
                   
                   
                  var id = agency.find('.type-id').attr('id');    
                  var agencyreqid = agency.closest(".job-table").find('.agency-id').val();
                  var perunitval = 0;
                  if($('#agency-rate-item-unit').val() == "2")
               	   perunitval = $('#agency-rate-item-perunit-expedite').val();
                  else
               	   perunitval = $('#agency-rate-item-perunit').val();
               	   
                  
				  var code = $('#agency-rate-item-code').val();
				  var value = $('#agency-rate-item-value').val();
				  var str = '';
				  var eFlag = false;
				  if($.trim(code) == "")
				   {
					  str +='Code is Required.';
					  eFlag = true;
				   }
				   if($.trim(value) == "")
				   {
					str +='Value is Required.';
					 eFlag = true;
				   }
				   else if(isNaN(value))
				   {
					   str +='Enter Numeric Value.';
					   eFlag = true;
				   }
				   $("#agency-rate-item-form-ErrorMsgDiv").html(str);
				   if(eFlag)
					   return;
                   var rateItemDetails={                    		
                   		
   						code:code,
   						codeDescription:$('#agency-rate-item-code-description').val(),
   						value:value,
   						unit:$('#agency-rate-item-unit').val(),
   						perUnit:perunitval,
   						reimbursable:$('#agency-rate-item-reimbursable').is(":checked"),
   						taxable:$('#agency-rate-item-taxable').is(":checked") ,
   						entityUserId:agencyreqid,
   						type:"AGENCY",
   						ccval:0,
   						jobId:agency.find('.agency-job_id').val()
   						
                       };
                   
                   
                   callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,id);

                   $( this ).dialog( "close" );
               }
           }
           },
           "ApplyRateToJob": {
        	   text: "Apply rate item to job",
        	   id: "applyMasterRate",
        	   
        	   click: function(){
        		   var block = $(this).find('.block-id').val();
                   var agency = $('#' + block);
                   var id = agency.find('.type-id').attr('id');    
        		   var existingRateItem={ 
						code:$('#agency-rate-item-code').val(),
						codeDescription:$('#agency-rate-item-code-description').val(),
						value:$('#agency-rate-item-value').val(),
						unit:$('#agency-rate-item-unit').val(),
						perUnit:$('#agency-rate-item-perunit').val(),
						reimbursable:$('#agency-rate-item-reimbursable').is(":checked"),
						taxable:$('#agency-rate-item-taxable').is(":checked") ,
						entityUserId:agency.closest(".job-table").find('.agency-id').val(),						
						jobId:agency.find('.agency-job_id').val()
                  };
        		   callAjaxToSaveAndApplyRateItem(existingRateItem, id); 
        		   $( this ).dialog( "close" );
        	   }   
           },
           Cancel: function() {
               $( this ).dialog( "close" );
           }
       },
       close: function() {
//           alert($(this).attr("id"));
           allAgencyFields.val( "" ).removeClass( "ui-state-error" );
       },
       open: function(event, ui) { 
    	   $(this).find("#applyMasterRate", ui.dialog || ui).hide(); 
       }

   });
   
   
   
   
   $( "#scopist-rate-item-form" ).dialog({
       autoOpen: false,
       height: 250,
       width: 950,
       modal: true,
       buttons: {
           "Create  scopist new rate item": function() {
               var bValid = true;
               allAgencyFields.removeClass( "ui-state-error" );

//               bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
               // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

               if ( bValid ) {
                   /*
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + name.val() + "</td>" +
                    "<td>" + email.val() + "</td>" +
                    "<td>" + password.val() + "</td>" +
                    "</tr>" );
                    */
                   var block = $(this).find('.block-id').val();
                   var agency = $('#' + block);
                   
                 
                
                 /*  agency.find('.scopist-id').val('0');
                   agency.find('.scopist-initial').val($("#scopist-initial").val())
                   agency.find('.scopist-name').val($("#scopist-name").val())
                   agency.find('.scopist-initial').focus();*/
                   
               var id = agency.find('.scopist-rate-item-id').attr('id');
                 
                   agency.find('.scopist-rate-item-id').val('0');                    
                   agency.find('.scopist-rate-item-code').val($('#scopist-rate-item-code').val());
                   agency.find('.scopist-rate-item-code-description').val($('#scopist-rate-item-code-description').val());
                   agency.find('.scopist-rate-item-value').val($('#scopist-rate-item-value').val());
                   agency.find('.scopist-rate-item-unit').val($('#scopist-rate-item-unit').val());
                   agency.find('.scopist-rate-item-perunit').val($('#scopist-rate-item-perunit').val());
                   agency.find('.scopist-rate-item-reimbursable').val($('#scopist-rate-item-reimbursable').val());
                   agency.find('.scopist-rate-item-taxable').val($('#scopist-rate-item-taxable').val());  
                   agency.find('.scopist-rate-item-perunit-expedite').val($('#scopist-rate-item-perunit-expedite').val());
                   agency.find('.scopist-rate-item-code').focus();
                   
                 var perunitval = 0;
                   if($('#scopist-rate-item-unit').val() == "2")
                	   perunitval = $('#scopist-rate-item-perunit-expedite').val();
                   else
                	   perunitval = $('#scopist-rate-item-perunit').val();
                   
                   //alert(agency.find('.scopist-job-id').val());
				   var code = $('#scopist-rate-item-code').val();
				   var value = $('#scopist-rate-item-value').val();
				   var str = '';
				   var eFlag = false;
                   if($.trim(code) == "")
				   {
					   str +='Code is Required.';
					   eFlag = true;
				   }
				   if($.trim(value) == "")
				   {
					   str +='Value is Required.';
					   eFlag = true;
				   }
				   else if(isNaN(value))
				   {
						str +='Enter Numeric Value;';
						eFlag = true;
				   }
				   $("#scopist-rate-item-form-ErrorMagDiv").html(str);
				   if(eFlag)
					   return;
                   var rateItemDetails={                    		
                   		
						code:code,
						codeDescription:$('#scopist-rate-item-code-description').val(),
						value:value,
						unit:$('#scopist-rate-item-unit').val(),
						perUnit:perunitval,
						reimbursable:$('#scopist-rate-item-reimbursable').is(":checked"),
						taxable:$('#scopist-rate-item-taxable').is(":checked") ,
						entityUserId:$('.scopist-id').val(),
						type:"SCOPIST",
						ccval:0,
						jobId:agency.find('.scopist-job-id').val(),
						jobId:$('.jobId').val()
						
                   };
                    
                   callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,id);
                   
                   $( this ).dialog( "close" );
               }
           },
           Cancel: function() {
               $( this ).dialog( "close" );
           }
       },
       close: function() {
//           alert($(this).attr("id"));
           allAgencyFields.val( "" ).removeClass( "ui-state-error" );
       }
   });
    
 

    $( "#proofer-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a proofer": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );

                if ( bValid ) {
                	var block = $(this).find('.block-id').val();
                	var agency = $('#' + block);
                	agency.find('.proofer-initial').val($("#proofer-initial").val())
                    agency.find('.proofer-name').val($("#proofer-name").val())
                    agency.find('.proofer-initial').focus();
                	agency.closest(".job-table").find(".proofer-rate-item-code").val("");
                    agency.closest(".job-table").find(".proofer-rate-item-id").val(0);
                	var initial = $("#proofer-initial").val();
                    var name = $("#proofer-name").val();
                    var jobId = agency.closest(".job-table").find(".selectedjobid").val();
					var str = '';
					var eFlag = false;
					var  initial = $("#proofer-initial").val();
					var name = $("#proofer-name").val();
					if($.trim(initial) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim(name) == "")
					{
						str +='Name is Required.';
						eFlag = true; 
					}
					$("#proofer-form-errorMsgDiv").html(str);
					if(eFlag)
						return;
					
                	 var prooferval ={     
                  			"initial":initial,
                  			"name":name		
                  			
                  	};
                  	 $.ajaxSetup({
                		   jsonp: null,
                		   jsonpCallback: null
                		});

                	    $.ajax({
                		  type:'POST',
                		  url: 'qgl-log-detail-accounting.action?createProofer',
                		  dataType: 'json',
                		  data: {proofer:JSON.stringify(prooferval)},
                			 
                		  success: function(result){
                              agency.find('.proofer-id').val(result);
                              var obj = {
                   			};

                   	         obj["value"] = initial+" "+name;
                   	         obj["id"] = result;
                   	         obj["initial"] =initial;
                   	         obj["lastName"] = name;
                   	         obj["firstName"] = name;
                   	          proofers.push(obj);
                   	       
                         	  $("#prooferlink"+jobId).html("<a href='javascript:{getRateTableId("+result+","+jobId+",\"PROOFER\")}'>"+initial+"</a>");
                         	 $("#prooferRateId"+jobId).val(0);
                         	  $(".proofer-initial").quiggleJobAutoComplete(proofers, '.proofer-id',"#proofer-form",0,'prooferlink');
                              
                		 },
                		  error:function() { 
                			  
                		  }
                   	});

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	var block = $(this).find('.block-id').val();
            	var agency = $('#' + block);
            	 var jobId = agency.closest(".job-table").find(".selectedjobid").val();
            	 $("#prooferlink"+jobId).html("");
            	$("#prooferId"+jobId).val(0);
     			$("#prooferRateId"+jobId).val(0);
     			 agency.closest(".job-row").find(".proofer-initial").val("");
            	 agency.closest(".job-row").find(".proofer-initial").focus();
                $( this ).dialog( "close" );
            }
        },
        close: function(event, ui) {
        	if ( event.originalEvent && 
                    $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
        		var block = $(this).find('.block-id').val();
            	var agency = $('#' + block);
            	 var jobId = agency.closest(".job-table").find(".selectedjobid").val();
            	 $("#prooferlink"+jobId).html("");
     			$("#prooferId"+jobId).val(0);
     			$("#prooferRateId"+jobId).val(0);
            	 agency.closest(".job-row").find(".proofer-initial").val("");
            	 agency.closest(".job-row").find(".proofer-initial").focus();
	        }
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            $(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a proofer");
            $(this).find("#proofer-name").val("");
			$(this).find("#proofer-name").parent().css("display", "block");
			$(this).find("#proofer-name").parent().parent().next().css("display", "none");
        }
    });

});


function ajaxCallToGetMasterRateItems(masterRateTableType){
	  $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'rate-template.action?getMasterRateItemsVoList',
		  dataType: 'json',
		  data: {rateTableType: masterRateTableType },
		  success: function(result){
			 
			  setMasterRateItems(result, masterRateTableType);
		 },
		  error:function() { 
			  
		  }
	});
}

function setMasterRateItems(result, masterRateTableType){
	if(masterRateTableType==1){
		masterRateItemsARArray=[];
		masterRateCodesARArray=[];
		if(result!=null && result.length>0){
			for(var i=0;i<result.length;i++){
				var masterRateItemAR={
		            codeName: result[i].codeName,
		            description: result[i].userRateItemDescription,
		            priceType: result[i].unit,
		            unitType: result[i].perUnit,
		            rateItemId: result[i].userRateItemId
		        };
				masterRateItemsARArray.push(masterRateItemAR);
				masterRateCodesARArray.push(result[i].codeName.toLowerCase());
			}
			masterRateItemsARArray.join(", ");
			masterRateCodesARArray.join(", ");
		}
		
	}	
	else{
		masterRateItemsAPArray=[];
		masterRateCodesAPArray=[];
		
		if(result!=null && result.length>0){
			for(var i=0;i<result.length;i++){
				var masterRateItemAP={
		            codeName: result[i].codeName,
		            description: result[i].userRateItemDescription,
		            priceType: result[i].unit,
		            unitType: result[i].perUnit
		        };
				masterRateItemsAPArray.push(masterRateItemAP);
				masterRateCodesAPArray.push(result[i].codeName.toLowerCase());
			}
			masterRateItemsAPArray.join(", ");
			masterRateCodesAPArray.join(", ");
		}
	}		
}

 function callAjaxToSaveAndApplyRateItem(rateItemDtls, id){
	 
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'rate-template.action?mapMasterRateItemToJob',//name of action?name of method in action
		  dataType: 'json',
		  data: {rateItemDtls:JSON.stringify(rateItemDtls)},
			 
		  success: function(result){

			  $('#'+id).val(result.rateItemId);
		  },
		  error:function() { 
			  
		  }
	});
	
 }
function decimalNumbervalidtion(eleVal){
			var flag=true;
			if(isNaN(eleVal))
				flag =false;
			return flag;
		}
	function saveAdminstrativeHoursInJob(actualUserId,jobId){
	var str ='';	 
	var flag = true;
	var errmsg = $('#errorDiv');
	var skillAdminHrs = $('#skillAdminHrsId').val();
	
	var defaultSkillType =  $('input[name=hrstodoname]:radio:checked').val();
	var flag= decimalNumbervalidtion(skillAdminHrs);
	if(!flag)
	{
		
		$('#errorDiv').text("Enter Numeric Value.").addClass( "ui-state-highlight").css({"background":"#FFE4DD", "margin-bottom": "5px", "width": "250px", "padding": "3px", "font-family": "verdana","font-weight": "bold","color":"#000"});
    
		
		return;
	}
	if(flag)
		  {
$("#errorDiv").empty();
			$("#errorDiv").removeClass("errdiv");
 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?saveAdminstrativeHoursInJob',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId,skillAdminHrs:skillAdminHrs,defaultSkillType:defaultSkillType},
			 
		  success: function(result){
			 
				caluculateAllHours(jobId);
				$('#errorDiv').text("Administrative Hours saved Successfully").addClass("alert alert-success");
			$('.billingestimatePages').closest("div").next().find("input:visible").focus();
					setTimeout("closewindow()",2000);
			             
		  },
		  error:function() { 
			  
		  }
 	});	
		  }
}

function closewindow()
{
	$("#estimatePages-form").dialog("destroy");
}

function callAjaxToDisplayAdminstrativeHours(actualUserId,jobId){	
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?checkIfHoursToPerFormExist',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId},
			 
		  success: function(result){
			  if(result!=null){
				 //showError(userType, agency);
				//quiggleJobAutoComplete(result, '.est-id',"#estimatePages-form");
				showDialogue(result);
			  }            
		  },
		  error:function() { 
			  
		  }
 	});	
	
}

function showDialogue(result)
{
	
	var str='';
	str +='<div id="errorDiv"></div>';
	 str+=' <fieldset>'
     str+=' <div style="font-size: 14px;font-family: verdana;">';
     str+='<input type="hidden" name="block-id" class="block-id" value=""/>';
     for(var i=0;i<result.length;i++)
	{ 
		 if(result[i].defaultSkillType == 1)
		{
			 str +='<div id="regularDefaultDiv" class="selectedTask">';
    str+='<input type="radio" name="hrstodoname" class="hrstodoname"  id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="regularDefaultDiv">';
			str+='<input type="radio" name="hrstodoname" class="hrstodoname"  id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}

	str+=' <span class="label">Regular</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	 if(result[i].defaultSkillType == 2)
		{
		  str +='<div id="denseDefaultDiv" class="selectedTask">';
		 str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="denseDefaultDiv">';
str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Dense</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	
	 if(result[i].defaultSkillType == 3)
		{
		str +='<div id="easyDefaultDiv" class="selectedTask">';
    str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all" style="margin-left:4px;" checked="true"/>';
	 
		}
		else
		{
			 str +='<div id="easyDefaultDiv">';
	str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Easy</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br><br>';
	str +='<div style="font-size:11px;">(To change the values of default fields above, please do so from your Profile page.)</div><br>';
	str +='<div style="font-size:12px;">';
	str+=' <label for="skillAdminHrs">FOR THIS PARTICULAR JOB: Administrative Hours</label>';
	str+='<input type="text" maxlength="10" id="skillAdminHrsId" value="'+result[i].administrativeHours+'" name="skillAdminHr" style="width:60px;height:18px;border-radius: 3px 3px 3px 3px;border:1px solid #ccc;margin-left:1px;padding:3px;display: inline-table;" class="decimalnumberVal skillAdminHrs"/>';
	str +='</div>';
	}
	str+='</div>';
    str+=' </fieldset>';
	$("#estimatePages-formInnerDiv").html(str);
      
}





